﻿using ClientAppraise.ViewModels.Validator;
using ClientAppraise.Views.Pages.Users.Org;
using ClientAppraise.Views.Pages.Users.Org.Admin;
using ClientInfrastructure.Util.Helper;
using CommunityToolkit.Mvvm.Input;
using ShareCode.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClientDao.User;
using ShareCode.Dto.User.Org.Admin;
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using System.Windows;
using Wpf.Ui.Controls;
using ClientInfrastructure.Config;
using System.IO;

namespace ClientAppraise.ViewModels.Pages.Users.Org.Admin
{
    public partial class IndexViewModel(UserOrgDal pDal) : ObservableObject
    {
        readonly UserOrgDal dal = pDal;
        [ObservableProperty]
        private ObservableCollection<AdminListDto> adminList = [];

        private readonly PagingDto searchDto = new();


        [RelayCommand]
        public void Add()
        {
            App.MyNavigation.NavigateWithHierarchy(typeof(NewPage));
        }

        [RelayCommand]
        public void ItemClick(long id)
        {
            App.MyNavigation.NavigateWithHierarchy(typeof(DetailPage));
        }


        [RelayCommand]
        public async Task RefreshOrgListAsync()
        {
            void updateData(ResultDto<PagingWithDataModel<AdminListDto>> data)
            {
                if (!Application.Current.Dispatcher.CheckAccess())
                {
                    Application.Current.Dispatcher.Invoke(new Action(() => updateData(data)));
                    return;
                }

                if (data.Success)
                {
                    var data2 = data.Data!;

                    data2.List?.ForEach(item => { if (item.OrgEntity == null) return; item.OrgEntity.Ico = Path.Combine(MyAppContextModel.Obj.ConfigModel.ApiServer??"", item.OrgEntity?.Ico??"").Replace('\\','/'); AdminList.Add(item); });

                    searchDto.Init(data2);
                }

            }

            await App.MyContentDialog.ShowRingLoadingAsync(async () =>
            {
                try
                {
                    var data = await dal.AdminList(searchDto);

                    updateData(data);

                }
                catch (Exception ex)
                {
                    App.MySnackbar.Danger(ex.Message, ex.Message);
                }
                finally
                {
                    App.MyContentDialog.CloseLoading();
                }
            });
        }


    }
}
